<?php
/**
 * File: DingTalk.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 14:39
 */

namespace Common\Extend\DingTalk;

use Common\Extend\DingTalk\Client\SdkClient;
use Common\Extend\DingTalk\Client\HttpClient;

class DingTalk
{
    public $corpId, $corpSecret, $agentId, $host;
    protected $token;
    //缓存
    const DINGTALK_TOKEN = "dingtalk_token";
    const CACHE_EXPIRE = 3600;

    public function __construct(array $config = [])
    {
        $dingTalkConfig = C('DINGTALK');
        //配置参数
        $this->corpId = $dingTalkConfig['CorpId'];
        $this->corpSecret = $dingTalkConfig['CorpSecret'];
        $this->agentId = $dingTalkConfig['AgentId'];
        $this->host = $dingTalkConfig['Host'];
        //检测token缓存是否存在
        $token = S(self::DINGTALK_TOKEN);
        if (!empty($token)) {
            $this->token = $token;
        } else {
            $this->token = $this->getAccessToken();
        }
    }

    /**
     * http请求客户端
     * @return HttpClient
     */
    protected function http()
    {
        $client = HttpClient::getInstance(['host' => $this->host]);
        if (isset($this->token)) {
            $client->setToken($this->token);
        }
        return $client;
    }

    protected function sdk()
    {
        $client = SdkClient::getInstance();
        if (isset($this->token)) {
            $client->setToken($this->token);
        }
        return $client;

    }

    /**
     * 获取token
     * @return mixed
     */
    protected function getAccessToken()
    {
        $data['corpid'] = $this->corpId;
        $data['corpsecret'] = $this->corpSecret;
        //清除旧token
        $this->http()->clearToken();
        $res = $this->http()->get('gettoken', $data);
        //存入缓存
        S(self::DINGTALK_TOKEN, $res['access_token'], self::CACHE_EXPIRE);
        return $res['access_token'];
    }

    /**
     * 获取企业用户数量
     * @param int $onlyActive
     * @return mixed
     */
    public function getUserNumber($onlyActive = 0)
    {
        return $this->http()->get('user/get_org_user_count', ['onlyActive' => $onlyActive]);
    }

    /**
     * code-获取用户userId
     * @param $code
     * @return mixed
     */
    public function getUserId($code)
    {
        return $this->http()->get('user/getuserinfo', ['code' => $code]);
    }

    /**
     * userId-获取用户详情
     * @param $userId
     * @return mixed
     */
    public function getUserInfo($userId)
    {
        return $this->http()->get('user/get', ['userid' => $userId]);

    }

    /**
     * 获取管理员列表
     * @return mixed
     */
    public function getAdminList()
    {
        return $this->http()->get('user/get_admin', []);

    }

    /**
     * 获取部门列表
     * @return mixed
     */
    public function getDepartmentList()
    {
        return $this->http()->get('department/list', []);
    }

    /**
     * 获取部门详情
     * @param $departmentId
     * @return mixed
     */
    public function getDepartmentInfo($departmentId)
    {
        return $this->http()->get('department/get', ['id' => $departmentId]);

    }

    /**
     * 获取部门成员
     * @param $departmentId
     * @return mixed
     */
    public function getDepartmentUsers($departmentId)
    {
        return $this->http()->get('user/simplelist', ['department_id' => $departmentId]);

    }

    /**
     * 获取企业角色信息
     * @param int $size
     * @param int $offset
     * @return mixed
     */
    public function getRoleList($size = 20, $offset = 0)
    {
        $req = $this->sdk()->req('CorpRoleListRequest');
        $req->setSize(strval($size));
        $req->setOffset(strval($offset));
        return $this->sdk()->run($req);
    }

    /**
     * 获取角色组角色列表
     * @param $groupId
     * @return mixed
     */
    public function getGroupRoleList($groupId)
    {
        $req = $this->sdk()->req('CorpRoleGetrolegroupRequest');
        $req->setGroupId(strval($groupId));
        return $this->sdk()->run($req);
    }

    /**
     * 获取角色的员工列表
     * @param $roleId
     * @param int $size
     * @param int $offset
     * @return mixed
     */
    public function getRoleUserList($roleId, $size = 20, $offset = 0)
    {
        $req = $this->sdk()->req('CorpRoleSimplelistRequest');
        $req->setRoleId(strval($roleId));
        $req->setSize(strval($size));
        $req->setOffset(strval($offset));
        return $this->sdk()->run($req);
    }

    /**
     * 发送钉钉消息
     * @param array $ids 发送对象集合
     * @param string $msgType 消息类型：text,link,oa,markdown等
     * @param string $msg 消息内容
     * @param string $sendType 发送类型：个人，部门，全体
     * @return mixed
     */
    public function sendMessage($ids = [], $msg, $msgType = 'link', $sendType = 'user')
    {
        $req = $this->sdk()->req('CorpMessageCorpconversationAsyncsendRequest');
        $req->setAgentId(strval($this->agentId));
        $req->setMsgtype($msgType);
        $req->setMsgcontent($msg);

        if (!empty($ids)) {
            foreach ($ids as &$id) {
                $id = strval($id);
            }
        } else {
            return;
        }
        if ($sendType == 'user') {
            $req->setUseridList(implode(',', $ids));
            $req->setToAllUser("false");
        } else if ($sendType == 'department') {
            $req->setDeptIdList(implode(',', $ids));
            $req->setToAllUser("false");
        } else {
            $req->setToAllUser("true");
        }
        return $this->sdk()->run($req);
    }
}